﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;

namespace eVoting
{
    public partial class ResetPassword : System.Web.UI.Page
    {
        DBManager db;
        
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btn_submit_Click(object sender, EventArgs e)
        {
            db = new DBManager();
            int id = Int32.Parse((String)Session["id"]);
            User user = db.getUserById(id);

            string hashedPW = db.CreatePasswordHash(txt_oldpw.Text, user.pwSalt);
            if(hashedPW != user.password)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "javascript:alert('Wrong Password !');", true);
            }
            else
            {
                if (txt_newPW1.Text != txt_newPW2.Text)
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "javascript:alert('Passwords do not match !');", true);
                }

                else
                {
                    string newSalt = db.CreateSalt(10);
                    string newHashedPW = db.CreatePasswordHash(txt_newPW1.Text, newSalt);

                    if (db.changePW(newHashedPW, newSalt, user))
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "javascript:alert('Your Password has been changed succesfully !');", true);
                    }
                }
            }
        }
    }
}